package com.cz.adapter.chat;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.cz.R;
import com.cz.pojo.ChatRecord;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 *
 * 聊天记录适配器
 *
 */
public class ChatAdapter extends BaseAdapter {

    //聊天记录
    private ArrayList<ChatRecord> mList;
    private Context mContext;
    private LayoutInflater inflater;
    private HolderView holderView;


    public ChatAdapter(Context context, ArrayList<ChatRecord> list) {
        this.mContext = context;
        this.mList = list;
        inflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList == null ? null : mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_chat_record_list, null);
            holderView = new HolderView();
            holderView.tv_name = (TextView) convertView.findViewById(R.id.tv_chat_name);
            holderView.tv_record = (TextView) convertView.findViewById(R.id.tv_chat_record);
            holderView.tv_time = (TextView) convertView.findViewById(R.id.tv_chat_time);
            holderView.img_chat_head = (ImageView) convertView.findViewById(R.id.img_chat_head);
            convertView.setTag(holderView);
        } else {
            holderView = (HolderView) convertView.getTag();
        }
        ChatRecord chatRecord = mList.get(position);

        R.drawable drawable = new R.drawable();
        int resId=0;
        Field field= null;
        try {
            String headimg = chatRecord.getHeadimg();
            if(headimg==null){
                headimg = "icon";
            }
            field = R.drawable.class.getField(headimg);
            resId=(Integer)field.get(drawable);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        holderView.img_chat_head.setImageResource(resId);
        holderView.tv_name.setText(chatRecord.getUserid());
        holderView.tv_record.setText(chatRecord.getEndmessage());
        holderView.tv_time.setText(chatRecord.getEndtime());
        return convertView;
    }
    private class HolderView {
        private TextView tv_name;
        private TextView tv_record;
        private TextView tv_time;
        private ImageView img_chat_head;
    }

}
